<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" label-width="100px">
      <el-form-item label="请假类型">
        <el-select v-model="queryParams.leaveType" clearable>
          <el-option v-for="item in leaveTypeList" :key="item.id" :label="item.dictLabel"
                     :value="item.dictValue"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="请假时间">
        <el-date-picker clearable
                        v-model="queryParams.times"
                        type="date"
                        value-format="yyyy-MM-dd"
                        range-separator="至"
                        start-placeholder="开始日期"
                        end-placeholder="结束日期">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="申请单编号">
        <el-input
          v-model="queryParams.applyNo"
          placeholder="请输入申请单编号"
          clearable
          size="small"
          style="width: 150px"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-button type="primary" icon="el-icon-plus" size="mini" @click="handleAdd">创建请假申请</el-button>
    </el-row>

    <el-table v-loading="loading" :data="deployList">
      <el-table-column label="申请单编号" prop="applyNo" align="center" width="180">
        <template slot-scope="scope">
          <el-link type="primary" @click="handleView(scope.row)">{{scope.row.applyNo}}</el-link>
        </template>
      </el-table-column>
      <el-table-column label="学生姓名" align="center" prop="studentName" :show-overflow-tooltip="true"/>
      <el-table-column label="学生班级" align="center" prop="className" :show-overflow-tooltip="true"/>
      <el-table-column label="请假开始时间" align="center" prop="leaveStartTime" :show-overflow-tooltip="true"/>
      <el-table-column label="请假结束时间" align="center" prop="leaveEndTime" :show-overflow-tooltip="true"/>
      <el-table-column label="请假类型" align="center" prop="leaveType" :show-overflow-tooltip="true">
        <template slot-scope="scope">
          {{leaveTypeList.filter(function(item,index,arr){
          return item.dictValue==scope.row.leaveType
          })[0].dictLabel}}
        </template>
      </el-table-column>
      <el-table-column label="申请原因" align="center" prop="leaveRemarks" :show-overflow-tooltip="true"/>
      <el-table-column label="当前审批人" align="center" prop="currApprovedBy"/>
      <el-table-column label="申请单状态" align="center" prop="status">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.status==0" type="info">草稿</el-tag>
          <el-tag v-if="scope.row.status==1" type="primary">待审批</el-tag>
          <el-tag v-if="scope.row.status==2" type="danger">审批驳回</el-tag>
          <el-tag v-if="scope.row.status==3" type="success">审批通过</el-tag>
          <el-tag v-if="scope.row.status==4" type="danger">撤销</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime" :show-overflow-tooltip="true">
        <template slot-scope="scope">
          {{parseTime(scope.row.modifyTime)}}
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center">
        <template slot-scope="scope">
          <el-tooltip class="item" effect="dark" content="撤销申请" placement="top">
            <el-button
              size="mini"
              circle type="warning"
              icon="el-icon-refresh-left"
              v-if="scope.row.status==1"
              @click="cancelApply(scope.row)"
            />
          </el-tooltip>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />
    <el-dialog title="创建请假申请" :visible.sync="dialogVisible" width="70%" :before-close="handleClose">
      <el-form :model="leaveFormData" ref="leaveFormData" :rules="rules" label-width="120px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="班级" prop="classId">
              <el-select v-model="leaveFormData.classId" @change="getSutdentsAndClassName" v-if="!isView">
                <el-option v-for="item in classList" :key="item.id" :value="item.id"
                           :label="item.className"></el-option>
              </el-select>
              <label v-else>{{leaveFormData.className}}</label>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="学生" prop="studentId">
              <el-select v-model="leaveFormData.studentId" @change="getStudentName" v-if="!isView">
                <el-option v-for="item in students" :key="item.id" :value="item.id" :label="item.name"></el-option>
              </el-select>
              <label v-else>{{leaveFormData.studentName}}</label>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="请假开始时间" prop="leaveStartTime">
              <el-date-picker
                :disabled="isView"
                style="width:60%"
                v-model="leaveFormData.leaveStartTime"
                type="datetime"
                @change="startDays"
                value-format="yyyy-MM-dd HH:mm:ss"
                :picker-options="expireTimeOPtion"
                placeholder="选择开始日期时间">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="请假结束时间" prop="leaveEndTime">
              <el-date-picker
                :disabled="isView"
                style="width:60%"
                v-model="leaveFormData.leaveEndTime"
                @change="endDays"
                type="datetime"
                value-format="yyyy-MM-dd HH:mm:ss"
                :picker-options="expireTimeOPtion"
                placeholder="选择结束日期时间">
              </el-date-picker>
            </el-form-item>
          </el-col>

        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="请假总天数" prop="leaveTotalTime">
              <el-input type="text" v-model="leaveFormData.leaveTotalTime" style="width:60%" disabled></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="请假类型" prop="leaveType">
              <el-select v-model="leaveFormData.leaveType" style="width:60%" :disabled="isView">
                <el-option v-for="item in leaveTypeList" :key="item.id" :value="item.dictValue"
                           :label="item.dictLabel"></el-option>
              </el-select>
              <!-- <el-radio v-for="item in leaveTypeList" :key="item.id"
                  v-model="leaveFormData.leaveType" :label="item.dictValue" :disabled="isView">{{item.dictLabel}}</el-radio> -->
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="请假原因" prop="leaveRemarks">
          <el-input v-model="leaveFormData.leaveRemarks" type="textarea" :disabled="isView"></el-input>
        </el-form-item>
        <el-row>
          <el-col :span="12" v-if="!isView">
            <el-form-item label="下级审批部门" prop="deptId">
              <!-- <el-input v-model="leaveFormData.currApprovedBy" style="width:60%"/> -->
              <!--<el-tag v-for="item in userList" :key="item.id" style="margin-left: 3px;">{{item.userName}}</el-tag>
              <el-button type="info" plain size="mini" icon="el-icon-plus" @click="handleUser">选择审批人</el-button>
              <el-button type="info" plain size="mini" icon="el-icon-delete" @click="clearUser" v-if="ccUserList.length>0">清空审批人</el-button>-->
              <el-select v-model="leaveFormData.deptId"  placeholder="请选择" clearable>
                <el-option v-for="deptList in dept" :key="deptList.deptId" :label="deptList.deptName" :value="deptList.deptId">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="抄送人" prop="ccUsers">
              <el-tag v-for="item in ccUserList" :key="item.id" style="margin-left: 3px;">{{item.userName}}</el-tag>
              <el-button type="info" plain size="mini" icon="el-icon-plus" @click="handleCCUser" v-if="!isView">选择抄送人
              </el-button>
              <el-button type="info" plain size="mini" icon="el-icon-delete" @click="clearCCUser"
                         v-if="ccUserList.length>0 && !isView">清空抄送人
              </el-button>
            </el-form-item>
          </el-col>
        </el-row>


      </el-form>
      <div>
        <approvalHistory :processId="leaveFormData.processId"
                         v-if="leaveFormData.processId && dialogVisible"></approvalHistory>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm" v-if="!isView">提 交</el-button>
        <el-button @click="handleClose">取 消</el-button>
      </div>
    </el-dialog>

    <el-dialog :visible.sync="dialogVisibleUser" title="选择人员">
      <deptUser @getTaskUser="getApprovedUser" :multiple="false" v-if="dialogVisibleUser"></deptUser>
    </el-dialog>

    <el-dialog :visible.sync="dialogVisibleCCUser" title="选择抄送人员">
      <deptUser @getTaskUser="getCCuser" :multiple="true" v-if="dialogVisibleCCUser"></deptUser>
    </el-dialog>
  </div>
</template>

<script>
    import {getToken} from "@/utils/auth";
    import {findLeaveApplyPageList, createLeaveApply, cancelLeaveApply} from "@/api/workflow/studentLeaveWithdrawal"
    import {findClassByTeacher} from "@/api/classManage/classInfo";
    import {queryClassStudents} from "@/api/studentInfo/examResultEnter";
    import deptUser from '../../components/userSelect/deptUser.vue'
    import approvalHistory from '../../components/workflow/approvalHistory'
    import {treeselectAll} from "@/api/system/dept";
    import {listDeptAll} from "@/api/system/dept";

    export default {
        name: "Config",
        components: {
            approvalHistory,
            deptUser
        },
        data() {
            var validateDatePass = (rule, value, callback) => {
                if (this.leaveFormData.leaveStartTime >= this.leaveFormData.leaveEndTime) {
                    callback(new Error('结束时间要大于开始时间'));
                } else {
                    this.$refs['leaveFormData'].clearValidate(['leaveStartTime', 'leaveEndTime'])
                    callback();
                }
            };

            return {
                expireTimeOPtion: {
                    disabledDate(time) {
                        return time.getTime() <= Date.now() - 1 * 24 * 3600 * 1000 //如果没有后面的-8.64e7就是不可以选择今天的
                    },
                },
                // 遮罩层
                loading: true,
                // 选中数组
                ids: [],
                // 非单个禁用
                single: true,
                // 非多个禁用
                multiple: true,
                // 总条数
                total: 0,
                // 参数表格数据
                deployList: [],
                // 弹出层标题
                title: "",
                // 是否显示弹出层
                open: false,
                // 类型数据字典
                typeOptions: [],
                // 日期范围
                dateRange: [],
                // 查询参数
                queryParams: {
                    pageNum: 1,
                    pageSize: 10,
                    leaveType: null,
                    paramKey: undefined,
                    paramType: undefined
                },
                dialogVisible: false,
                dialogVisibleUser: false,
                dialogVisibleCCUser: false,
                leaveFormData: {
                },
                rules: {
                    leaveStartTime: [
                        {required: true, message: "请选择请假开始时间", trigger: "blur"},
                        {validator: validateDatePass, trigger: 'blur'}],
                    leaveEndTime: [
                        {required: true, message: "请选择请假结束时间", trigger: "blur"},
                        {validator: validateDatePass, trigger: 'blur'}],
                    leaveTotalTime: [{required: true, message: "请填写请假天数", trigger: "blur"}],
                    leaveType: [{required: true, message: "请选择请假类型", trigger: "blur"}],
                    leaveRemarks: [{required: true, message: "请填写请假原因", trigger: "blur"}],
                    classId: [{required: true, message: "请选择班级", trigger: "blur"}],
                    studentId: [{required: true, message: "请选择学生", trigger: "blur"}],
                    deptId: [{required: true, message: "请选择审批部门", trigger: "blur"}]
                },
                leaveTypeList: [],
                isView: false,
                deptOptions: [],
                props: {multiple: true},
                ccUserList: [],
                userList: [],
                classList: [],
                students: [],
                dept: [],
            };
        },
        computed: {
            headers() {
                return {
                    'Authorization': getToken()
                }
            }
        },
        created() {
            this.getList();
            this.getClass();
            this.getTreeselect();
            this.getDeptSelect();
            this.getDicts("leave_type").then(response => {
                this.leaveTypeList = response.data;
            });
            this.leaveFormData.leaveTotalTime = ((new Date(this.leaveFormData.leaveEndTime).getTime() -
                new Date(
                    this.leaveFormData.leaveStartTime).getTime()) / 1000 / 60 / 60 / 24).toFixed(2)
        },
        methods: {
            startDays(e) {
                this.$forceUpdate()
                this.$set(this.leaveFormData,"leaveStartTime",e)
                console.log(this.leaveFormData.leaveStartTime)
                console.log(this.leaveFormData.leaveEndTime)
                if (this.leaveFormData.leaveEndTime && this.leaveFormData.leaveStartTime) {
                    this.leaveFormData.leaveTotalTime = ((new Date(this.leaveFormData.leaveEndTime).getTime() -
                        new Date(
                            this.leaveFormData.leaveStartTime).getTime()) / 1000 / 60 / 60 / 24).toFixed(2)
                }
                console.log(this.leaveFormData.leaveTotalTime)
            },
            endDays(e) {
                this.$set(this.leaveFormData,"leaveEndTime",e)
                console.log(this.leaveFormData.leaveStartTime)
                console.log(this.leaveFormData.leaveEndTime)
                if (this.leaveFormData.leaveEndTime && this.leaveFormData.leaveStartTime) {
                    this.leaveFormData.leaveTotalTime = ((new Date(this.leaveFormData.leaveEndTime).getTime() -
                        new Date(
                            this.leaveFormData.leaveStartTime).getTime()) / 1000 / 60 / 60 / 24).toFixed(2)
                }
                console.log(this.leaveFormData.leaveTotalTime)
            },
            getDeptSelect() {
                listDeptAll().then(resp => {
                    this.dept = resp.data
                })
            },
            getSutdentsAndClassName(classIdParam) {
                let classItme = this.classList.filter(item => {
                    return item.id == classIdParam;
                });
                if (classItme.length > 0) {
                    this.leaveFormData.className = classItme[0].className
                }

                queryClassStudents({classId: classIdParam}).then(resp => {
                    this.students = resp.data
                })
            },
            getStudentName(studentId) {
                let studentItme = this.students.filter(item => {
                    return item.id == studentId;
                })
                if (studentItme.length > 0) {
                    this.leaveFormData.studentName = studentItme[0].name
                }
                console.log(this.leaveFormData)
            },
            getClass() {//查询当前用户管理的班级
                findClassByTeacher().then(resp => {
                    this.classList = resp.data
                })
            },
            clearUser() {
                this.userList = []
                this.leaveFormData.currApprovedBy = null
            },
            clearCCUser() {
                this.ccUserList = []
                this.leaveFormData.currApprovedBy = null
            },
            getApprovedUser(data, isClose) {
                this.userList = data
                if (data) {
                    let ccUser = []
                    for (let i = 0; i < data.length; i++) {
                        ccUser.push(data[i].userName)
                    }
                    this.leaveFormData.currApprovedBy = ccUser.join(',')

                }
                this.$refs['leaveFormData'].clearValidate('ccUserList')
                this.dialogVisibleUser = isClose
            },
            getCCuser(data, isClose) {
                this.ccUserList = data
                if (data) {
                    let ccUser = []
                    for (let i = 0; i < data.length; i++) {
                        ccUser.push(data[i].userName)
                    }
                    this.leaveFormData.ccUsers = ccUser.join(',')

                }
                this.$refs['leaveFormData'].clearValidate('ccUserList')
                this.dialogVisibleCCUser = isClose
            },
            handleUser() {
                this.dialogVisibleUser = true
            },
            handleCCUser() {
                this.dialogVisibleCCUser = true
            },
            changeDept(item) {
                console.log(item)
                if (item.length > 0) {
                    let depts = []
                    for (let i = 0; i < item.length; i++) {
                        depts.push(item[i].join(','))
                    }
                    this.leaveFormData.approvedDept = depts.join(';')
                }

            },
            /** 查询部门下拉树结构 */
            getTreeselect() {
                treeselectAll().then(response => {
                    this.deptOptions = response.data;
                });
            },
            /** 查询参数列表 */
            getList() {
                this.loading = true;
                findLeaveApplyPageList(this.queryParams).then(response => {
                        this.deployList = response.data.list;
                        this.total = response.data.total;
                        this.loading = false;
                    }
                );
            },
            // 表单重置
            reset() {
                this.form = {
                    id: undefined,
                    paramName: undefined,
                    paramKey: undefined,
                    paramValue: undefined,
                    paramType: "Y",
                    remark: undefined
                };
                this.resetForm("form");
            },
            /** 搜索按钮操作 */
            handleQuery() {
                this.queryParams.pageNum = 1;
                this.getList();
            },
            /** 重置按钮操作 */
            resetQuery() {
                this.dateRange = [];
                this.resetForm("queryForm");
                this.queryParams = {
                    pageNum: 1,
                    pageSize: 10,
                    leaveType: null,
                    times: null,
                    applyNo: null
                }
                this.handleQuery();
            },
            resetForm() {
                this.leaveFormData = {
                    leaveStartTime: undefined,
                    leaveEndTime: undefined,
                    leaveTotalTime: undefined,
                    leaveType: undefined,
                    leaveRemarks: undefined,
                }
            },
            handleView(row) {
                this.isView = true
                this.leaveFormData = row
                if (row.ccUsers) {
                    this.ccUserList = row.ccUsers.split(',').map(item => {
                        return {userName: item}
                    })
                }

                //   const deptArray = row.approvedDept.split(';')
                //   let approvedDeptArray = []
                //   for(let i=0;i<deptArray.length;i++){
                //     let dataIntAry = deptArray[i].split(',')
                //     approvedDeptArray.push(dataIntAry.map(item=>{
                //       return +item
                //     }))
                //   }
                //   this.leaveFormData.approvedDeptModel = approvedDeptArray
                this.dialogVisible = true
            },
            handleClose(done) {
                this.dialogVisible = false
            },
            handleAdd() {
                this.resetForm()
                this.dialogVisible = true
                this.isView = false
                this.ccUserList = []
                this.userList = []
            },
            submitForm() {
                console.log(this.leaveFormData);
                this.$refs["leaveFormData"].validate(valid => {
                    if (valid) {
                        this.leaveFormData.status = 1
                        createLeaveApply(this.leaveFormData).then(resp => {
                            this.$message({message: '提交成功', type: 'success'});
                            this.dialogVisible = false
                            this.getList()
                        })
                    }
                })
            },
            cancelApply(row) {
                this.$confirm('取消要撤销请假申请吗?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    const applyData = {
                        processInstanceId: row.processId
                    }
                    this.loading = true
                    cancelLeaveApply(applyData).then(resp => {
                        this.$message({type: 'success', message: '撤销成功!'});
                        this.getList()
                    })

                })
            },
            computeDays() {
                this.leaveFormData.leaveStartTime
                this.leaveFormData.leaveEndTime
            },
            compareDate(start, end) {
                if (start == null || start.length == 0 || end == null || end.length == 0) {
                    return 0;
                }

                var arr = start.split("-");
                var starttime = new Date(arr[0], arr[1], arr[2]);
                var starttimes = starttime.getTime();

                var arrs = end.split("-");
                var endtime = new Date(arrs[0], arrs[1], arrs[2]);
                var endtimes = endtime.getTime();

                var intervalTime = endtimes - starttimes;//两个日期相差的毫秒数 一天86400000毫秒
                var Inter_Days = ((intervalTime).toFixed(2) / 86400000) + 1;//加1，是让同一天的两个日期返回一天

                return Inter_Days;
            }
        }
    };
</script>
